package org.example.com.RocketMq.service;

import lombok.extern.slf4j.Slf4j;
import org.example.com.RocketMq.dto.MqTransactionLog;
import org.example.com.RocketMq.dto.UserCharge;
import org.example.com.RocketMq.mapper.MqTransactionLogMapper;
import org.example.com.RocketMq.mapper.UserChargeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class RocketService {

    @Autowired
    private MqTransactionLogMapper mqLogMapper;

    @Autowired
    private UserChargeMapper userMapper;

    @Transactional
    public int addBalance(UserCharge userCharge, String transactionId){
        MqTransactionLog mqTransactionLog = new MqTransactionLog();
        mqTransactionLog.setTransactionId(transactionId);
        mqTransactionLog.setLog(transactionId+":事务执行成功");
        userMapper.addUserCharge(userCharge);
        mqLogMapper.addMqTransactionLog(mqTransactionLog);
        return 1;
    }

    public Map<String,Object> selectByPrimaryKey(String transactionId){
        MqTransactionLog mqTransactionLog = new MqTransactionLog();
        mqTransactionLog.setTransactionId(transactionId);
        MqTransactionLog mqTransactionLog1 = mqLogMapper.selectByPrimaryKey(transactionId);
        HashMap<String, Object> map = entityToMap(mqTransactionLog1);
        return map;
    }

    public <T> HashMap<String,Object> entityToMap(T object) {
        HashMap<String,Object> convertMap = null;

        if (object == null){
            return null;
        }else {
            convertMap = new HashMap<>();
            for (Field declaredField : object.getClass().getDeclaredFields()) {
                declaredField.setAccessible(true);
                try {
                    convertMap.put(declaredField.getName(),declaredField.get(object));
                }catch (Exception e){
                    log.error("",e);
                }
            }
        }
        return convertMap;
    }
}
